package com.example.Servlet;

import com.example.Service.UserService;
import com.example.pojo.User;
import com.example.pojo.UserVO;
import com.google.gson.Gson;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    private String message;

    public void init() {
        message = "樊诗涵!";
    }

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5501");
        resp.setHeader("Access-Control-Allow-Methods", "POST");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setStatus(HttpServletResponse.SC_OK);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 设置响应格式（防中文乱码）
        resp.setContentType("application/json;charset=UTF-8");
        resp.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5501");
        resp.setHeader("Access-Control-Allow-Credentials", "true");

        // 2. 读取前端JSON（注册信息+验证码）
        BufferedReader br = new BufferedReader(req.getReader());
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String jsonStr = sb.toString();
        System.out.println("前端传入JSON：" + jsonStr);

        // 3. 解析JSON到UserVO（Gson需要UserVO有无参构造）
        Gson gson = new Gson();
        UserVO userVO = gson.fromJson(jsonStr, UserVO.class);

        // 4. 关键修复：UserVO转User（处理字段类型/名称匹配）
        User user = new User();
        try {
            // UserVO的userId是String，User的userId是int，需要强制转换
            user.setUserId(Integer.parseInt(userVO.getUserId()));
        } catch (NumberFormatException e) {
            // 账号不是数字时，返回错误
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("code", 500);
            errorMap.put("msg", "账号必须是数字");
            resp.getWriter().write(gson.toJson(errorMap));
            return;
        }
        user.setUserPwd(userVO.getUserPwd()); // 密码（字符串，直接赋值）
        user.setUserPhone(userVO.getUserPhone()); // 手机号（直接赋值）
        // 注意：UserVO是userAvtor（头像），User是userAuator（权限），这里给默认值
        user.setUserAuator("普通用户"); // 注册用户默认权限

        // 5. 获取用户输入的验证码（从UserVO中，字段已修复）
        String userInputCheckNum = userVO.getCheckNum();
        // 校验验证码是否为空
        if (userInputCheckNum == null || userInputCheckNum.trim().isEmpty()) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("code", 500);
            errorMap.put("msg", "请输入验证码");
            resp.getWriter().write(gson.toJson(errorMap));
            return;
        }

        // 6. 获取后端生成并保存的验证码（从ServletContext）
        ServletContext application = req.getServletContext();
        String systemCheckNum = (String) application.getAttribute("checkNum");

        // 7. 验证码逻辑：先判断是否过期
        Map<String, Object> resultMap = new HashMap<>();
        if (systemCheckNum == null) {
            resultMap.put("code", 500);
            resultMap.put("msg", "验证码已过期，请刷新重试");
            resp.getWriter().write(gson.toJson(resultMap));
            return;
        }

        // 8. 验证码比对（忽略大小写，提升用户体验）
        if (systemCheckNum.equalsIgnoreCase(userInputCheckNum.trim())) {
            // 验证码正确，执行注册
            UserService userService = new UserService();
            try {
                int flag = userService.addUser(user);
                if (flag > 0) {
                    resultMap.put("code", 200);
                    resultMap.put("msg", "注册成功");
                } else {
                    resultMap.put("code", 500);
                    resultMap.put("msg", "注册失败");
                }
            } catch (RuntimeException e) {
                // 捕获数据库异常（比如账号重复）
                resultMap.put("code", 500);
                resultMap.put("msg", "注册失败：账号已存在");
                e.printStackTrace();
            }
        } else {
            // 验证码错误
            resultMap.put("code", 500);
            resultMap.put("msg", "验证码错误，请重新输入");
        }

        // 9. 返回结果给前端
        String resultJsonStr = gson.toJson(resultMap);
        System.out.println("后端返回结果：" + resultJsonStr);
        resp.getWriter().write(resultJsonStr);
    }
}